import vue from "vue"
import request from "./request.js"
//#ifdef H5
//import wechat from "./../common/wechat.js"
//#endif
const api = {
	//轮播图的跳转
	bannerUrl(iosUrl, obj) {
		let urlArr = ["", "/pages/seller/shopIndex?shopId=", "", "/pages/product/product?proId=", "资金首页",
			"/pages/timeBear/index", "/pages/user/enter1", "/pages/lifeCir/artivDeails?type=2&id=", "/pages/capital/gameList",
			"/pages/user/user", "/pages/user/userinfo", "webview", "/pages/user/user", "/pages/order/order",
			"/pages/order/timeOrder", "/pages/order/gameOrder", "", "", "", "", "/pages/user/refunList"
		];
		if (iosUrl) {
			let url = JSON.parse(iosUrl);
			console.log(url);
			if (url.category == 4) {
				uni.switchTab({
					url: "/pages/capital/index"
				})
			} else if (url.category == 11) {
				uni.navigateTo({
					url: "/pages/web/webView?url=" + url.linkurl
				})
			} else if (url.category == 1 || url.category == 3 || url.category == 7) {
				//goodType免费商城为6,联盟商家为5
				if (url.category == 3 && obj.goodsType == 6) {
					uni.navigateTo({
						url: "/pages/timeBear/proDetails?id=" + url.objid
					});
				} else {
					uni.navigateTo({
						url: urlArr[url.category] + url.objid
					});
				}
			} else {
				if (urlArr[url.category]) {
					uni.navigateTo({
						url: urlArr[url.category]
					})
				}
			}
		}
	},
	//商品的搜索
	searchUrl(productsource, cateId, shopId, classifyType) {

		uni.navigateTo({
			url: "/pages/public/search?source=" + (productsource || "") + "&cateId=" + (cateId || "") + "&shopId=" + (shopId ||
				"") + "&classifyType=" + (classifyType || "")
		})
	},
	isversion(callback) {
		request({
			url: "/version/minApplication",
			method: "GET",
			success(d) {
				//1为审核中。2为审核过
				callback(d)
			}
		})
	},
	//是否登录
	isLogin() {
		let that = this
		let userInfo = that.userInfo();
		//#ifndef MP
		if (!userInfo.mid) {
			that.wxAuth();
			return
		}
		//#endif
		if (!userInfo.phone) {
			that.bindPhone()
			return
		}
	},
	//绑定手机号
	bindPhone() {
		let that = this;
		uni.showModal({
			title: "温馨提示",
			content: "亲爱的乐驿享用户，为了您的正常使用，请进行手机号绑定完成注册。",
			showCancel: false,
			confirmText: "立即绑定",
			confirmColor: "#ee3535",
			success(res) {
				if(res.confirm){
					uni.reLaunch({
						url: "/pages/user/bindPhone"
					})
				}
			}
		})
	},
	//微信授权
	wxAuth() {
		let that = this;
		uni.showModal({
			title: "温馨提示",
			content: "亲爱的乐驿享用户，为了您的正常使用，请进行微信授权完成注册。",
			showCancel: false,
			confirmText: "一键授权",
			confirmColor: "#ee3535",
			success(res) {
				if(res.confirm){
					// #ifdef APP-PLUS
					that.appLogin()
					// #endif
					//#ifdef MP 
					that.logingFun()
					// #endif
					//#ifdef H5
					window.location.href =
						"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc74951e13a0c4885&redirect_uri=http://www.hnlxyj.com/wx/html/while.html&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect"
					//#endif
				}
				
			}
		})
	},
	//app登录回调
	appLoginFun(infoRes) {
		request({
			url: "/member/wxAuthorized",
			data: {
				unionid: infoRes.userInfo.unionId,
				openid: infoRes.userInfo.openId,
				gender: infoRes.userInfo.gender,
				headimgurl: infoRes.userInfo.avatarUrl,
				nickname: infoRes.userInfo.nickName,
				source: "APP",
				inviterId: uni.getStorageSync("shareId") || ""
			},
			success(d) {
				uni.hideLoading()
				uni.setStorageSync('mid', d.mid);
				uni.setStorageSync("openId", d.appOpenId);
				uni.setStorageSync("nickName", d.nickname);
				uni.setStorageSync("avatar", d.avatarUrl);
				uni.setStorageSync("phone", d.phone);
				uni.setStorageSync("unionId", infoRes.unionId);
				uni.setStorageSync('userInfo', d);
				uni.setStorageSync("wxAccount", d.wxAccount);
				if (d.phone) {
					let pages = getCurrentPages();
					let prevPage = pages[pages.length - 1];  
					//#ifdef APP-PLUS
					uni.reLaunch({
						url:"/"+prevPage.route  
					 })
					// uni.redirectTo({
					// 	url:"/pages/public/nack?url=/"+prevPage.route   
					// })
					//#endif
					
					//#ifndef APP-PLUS
					uni.navigateTo({
						url:"/pages/public/nack?url="+prevPage.route  
					})
					//#endif
				} else {
					uni.reLaunch({
						
						
						url: "/pages/user/bindPhone"
					})
				}
			}
		})
	},
	//app登录
	appLogin(infoRes) {
		let that = this;
		uni.login({
			provider: 'weixin',
			success(loginRes) {

				uni.getUserInfo({
					provider: 'weixin',
					success(infoRes) {
						that.appLoginFun(infoRes)
					}
				});
			},
			fail(err) {

				that.msg(err)
				//that.$api.msg("授权失败，请稍后重试") 
			}
		})


	},
	//登录
	login() {
		let that = this;
		uni.showModal({
			title: "温馨提示",
			content: "当前您还没有登录,前去登录",
			showCancel: false,
			success(res) {
				if (res.confirm) {
				    // #ifdef APP-PLUS
				    uni.reLaunch({
				    	url: "/pages/public/login"
				    })
				    // #endif
				    //#ifdef MP 
				    that.logingFun()
				    // #endif
				    //#ifdef H5
				    window.location.href =
				    	"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc74951e13a0c4885&redirect_uri=http://www.hnlxyj.com/wx/html/while.html&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect"
				    //#endif  
				}
				
			}
		})
	},
	//小程序登录
	logingFun() {
		console.log(12)
		let that = this;
		uni.getUserInfo({
			provider: "weixin",
			success: function(res) {
				console.log(res);
				uni.login({
					provider: "weixin",
					success(d) {
						console.log(d);
						request({
							url: "/member/wxAuthorized",
							data: {
								code: d.code,
								inviterId: uni.getStorageSync("shareId") || 0,
								headimgurl: res.userInfo.avatarUrl,
								nickname: res.userInfo.nickName,
								source: "SMALLJSAPI"
							},
							success(data) {
								console.log(data)
								uni.hideLoading()
								that.msg("登录成功")
								uni.setStorageSync("mid", data.mid);
								uni.setStorageSync("phone", data.phone);
								uni.setStorageSync("userInfo", data)
								uni.setStorageSync("unionId", data.unionId);
								//#ifdef MP
								uni.setStorageSync("openId", data.jsOpenId);
								//#endif
								//#ifdef APP-PLUS
								uni.setStorageSync("openId", data.openId);
								//#endif
								if (data.phone) {
									
									uni.navigateTo({
										url:"/pages/public/nack"
									})
									
								} else {
								
									uni.reLaunch({
										url: "/pages/user/bindPhone"
									})
								}
							}
						})

					}
				})
			},
			fail(e) {
				console.log(e);
			}
		})
	},
	//小程序 支付
	apply(d, source, type, proData) {
		//type 那里的支付 联盟商家为1,免费商城为2，大赢家为3
		let that = this;
		if (type == 3) {
			// #ifdef MP
			uni.requestPayment({
				provider: 'wxpay',
				timeStamp: d.timeStamp + "",
				nonceStr: d.nonceStr,
				package: d.packageValue,
				signType: d.signType,
				paySign: d.paySign,
				success: (res) => {

					uni.switchTab({
						url: "/pages/index/index"
					})
				},
				fail: (res) => {

				},
				complete: () => {
					this.loading = false;
				}
			})
			//#endif
			//#ifdef APP-PLUS
			uni.requestPayment({
				provider: "wxpay",
				timeStamp: JSON.stringify(d.timestamp),
				nonceStr: d.noncestr,
				package: d.package,
				signType: "MD5",
				paySign: d.sign,
				orderInfo: JSON.stringify({
					appid: d.appid,
					noncestr: d.noncestr,
					package: d.package,
					partnerid: d.partnerid,
					prepayid: d.prepayid,
					timestamp: d.timestamp,
					sign: d.sign,
				}),
				success: function(res) {
					uni.switchTab({
						url: "/pages/index/index"
					})
				},
				fail: function(res) {

				}
			});
			//#endif
			//#ifdef H5
			/* if (wechat && wechat.isWechat()) {
				wechat.wxPay({
					timestamp: d.timeStamp + "", // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
					nonceStr: d.nonceStr,
					package: d.packageValue,
					signType: d.signType,
					paySign: d.paySign,
					success: function(res) {
						// 支付成功后的回调函数
						uni.switchTab({
							url: "/pages/index/index"
						})
					},
					cancel: function(res) {
						that.applyCancel(tradeNo, type)
					}
				});
			} */
			//#endif
			return
		}
		let obj = {
			source: source,
			mid: that.isMid() || "",
			tradeNo: d.tradeNo,
			openid: uni.getStorageSync("openId"),
		}

		let tradeNo = d.tradeNo;

		let url = "/wechatpay/jsApiUnifiedOrder";

		if (type == 2) {
			url = "/timebean/jsApiPayPostage";
			obj = {
				openid: uni.getStorageSync("openId"),
				atoId: d.orderId,
				mid: that.isMid() || "",
				source: "APP"
			}
			//#ifdef MP
			obj.source = "SMALLJSAPI"
			//#endif
			//#ifdef H5
			obj.source = "JSAPI"
			//#endif
			tradeNo = d.orderId
		}



		request({
			url: url,
			data: obj,
			success(d) {
				// #ifdef MP
				uni.requestPayment({
					provider: 'wxpay',
					timeStamp: d.timeStamp + "",
					nonceStr: d.nonceStr,
					package: d.package,
					signType: d.signType,
					paySign: d.sign,
					success: (res) => {
						let path = "/pages/money/paySuccess?source=" + type + "&orderId=" + tradeNo;
						if (type == 1) {
							path += "&proData=" + JSON.stringify(proData)
						}
						uni.redirectTo({
							url: path
						})
					},
					fail: (res) => {
						that.applyCancel(tradeNo, type)
					},
					complete: () => {
						this.loading = false;
					}
				})
				//#endif
				//#ifdef APP-PLUS
				uni.requestPayment({
					provider: "wxpay",
					timeStamp: JSON.stringify(d.timestamp),
					nonceStr: d.noncestr,
					package: d.package,
					signType: "MD5",
					paySign: d.sign,
					orderInfo: JSON.stringify({
						appid: d.appid,
						noncestr: d.noncestr,
						package: d.package,
						partnerid: d.partnerid,
						prepayid: d.prepayid,
						timestamp: d.timestamp,
						sign: d.sign,
					}),
					success: function(res) {
						let path = "/pages/money/paySuccess?source=" + type + "&orderId=" + tradeNo;
						if (type == 1) {
							path += "&proData=" + JSON.stringify(proData)
						}
						uni.redirectTo({
							url: path
						})
					},
					fail: function(res) {
						that.applyCancel(tradeNo, type)
					}
				});
				//#endif
				//#ifdef H5
			/* 	if (wechat && wechat.isWechat()) {
					wechat.wxPay({
						timestamp: d.timeStamp + "", // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
						nonceStr: d.nonceStr,
						package: d.package,
						signType: d.signType,
						paySign: d.sign,
						success: function(res) {
							// 支付成功后的回调函数
							let path = "/pages/money/paySuccess?source=" + type + "&orderId=" + tradeNo;
							if (type == 1) {
								path += "&proData=" + JSON.stringify(proData)
							}
							uni.redirectTo({
								url: path
							})
						},
						cancel: function(res) {
							that.applyCancel(tradeNo, type)
						}
					});
				} */
				//#endif

			}
		})


	},
	//取消支付的回调
	applyCancel(tradeNo, type) {
		let that = this;
		//联盟商家取消支付
		if (type == 1) {
			request({
				url: "/wechatpay/cancelPay",
				data: {
					mid: that.isMid() || "",
					tradeNo: tradeNo
				},
				success(d) {
					uni.redirectTo({
						url: '/pages/order/order'
					})
				}
			})
		} else if (type == 2) {
			request({
				url: "/timebean/cancelPayPost",
				data: {
					orderId: tradeNo
				},
				success(d) {
					uni.redirectTo({
						url: '/pages/order/timeBearOrder'
					})
				}
			})
		}
	},
	//商品的跳转
	proUrl(source, id, item) {
		if ((item.productsource || item.producttype) && (item.productsource == 1 || item.producttype == 1)) {
			//淘宝
			uni.navigateTo({
				url: "/pages/product/proB2C?source=1&proId=" + id
			})
		} else if ((item.productsource || item.producttype) && (item.productsource == 3 || item.producttype == 3)) {
			//京东
			uni.navigateTo({
				url: "/pages/product/proB2C?source=3&proId=" + id
			})
		} else if ((item.productsource || item.producttype) && (item.productsource == 7 || item.producttype == 7)) {
			//拼多多
			uni.navigateTo({
				url: "/pages/product/proB2C?source=7&proId=" + id
			})
		} else if (source == 5) {
			//联盟商家
			uni.navigateTo({
				url: "/pages/product/product?proId=" + id
			})
		} else if (source == 6) {
			uni.navigateTo({
				url: "/pages/timeBear/proDetails?id=" + id
			})
		}
	},
	//提示消息
	msg(title, duration = 2000, mask = false, icon = 'none') {
		//统一提示方便全局修改
		if (Boolean(title) === false) {
			return;
		}
		uni.showToast({
			title,
			duration,
			mask,
			icon
		});
	},
	//用户信息
	userInfo() {
		var userInfo = {};
		//#ifndef MP
		uni.getStorage({
			key: "userInfo",
			success(res) {
				console.log(res);
				if (res.data) {
					userInfo = res.data
				} else {
					userInfo = false;
				}
			}
		})
		//#endif
		//#ifdef MP
		userInfo=uni.getStorageSync("userInfo");
		//#endif
		return userInfo
	},
	//用户id
	isMid() {
		var mid = uni.getStorageSync("mid");
		return mid

	},
	//时间转换
	format(shijianchuo) {
		//shijianchuo是整数，否则要parseInt转换
		var time = new Date(shijianchuo);
		var y = time.getFullYear();
		var m = time.getMonth() + 1;
		var d = time.getDate();
		var h = time.getHours();
		var mm = time.getMinutes();
		var s = time.getSeconds();
		return y + '.' + this.add0(m) + '.' + this.add0(d) + ' ' + this.add0(h) + ':' + this.add0(mm)
	},
	getImgBaseSrc() {
		//http://www.hnlxyj.com/wx/v2.0
		return "https://wx.hnlxyj.com/web/v2.0"
	},
	add0(m) {
		return m < 10 ? '0' + m : m
	},
	//查询默认地址
	defAddress(callback) {
		var isDef = false;
		var that = this;
		let mid = '61359';
		request({
			url: "/user/address/searchAddress",
			method: "GET",
			data: {
				mid: mid
			},
			success(d) {
				if (d.length == 0) {
					callback(false);
					uni.showModal({
						title: '温馨提示',
						content: '当前您还没有收货地址,去添加嘛',
						success: function(res) {
							if (res.confirm) {
								uni.navigateTo({
									url: "/pages/aduit/addressManage"
								})
							} else if (res.cancel) {
								return
							}
						}
					})
					return false;
				}

				d.forEach(item => {
					if (item.def == 1) {
						isDef = true;
						callback(item);

					}
				})
				if (!isDef) {
					that.msg("您还没有默认地址");
					return false;
				} else {
					return true;
				}
			}
		})
	}
}
export default api
